<?php

namespace Framework;

use App\Controllers\ErrorController;
use Framework\Middleware\Authorise;

class Router{
    protected $routes = [];
    private function registerRoute($method,$uri,$action,$middleware = []){
        // $arr = explode('@',$action);
        // inspectAndDie($arr);
        list($controller,$controllerMenthod)=explode('@',$action);
        // inspectAndDie($controllerMenthod);
        $this->routes[] = [
            'method' => $method,
            'uri' => $uri,
            'controller' => $controller,
            'controllerMethod' =>$controllerMenthod,
            'middleware' =>$middleware
        ];
    }
    /**
     * 添加一个 GET 路由
     * @param string $url
     * @param string $controller
     * @return void
     */
    public function addGet($uri,$controller,$middleware=[]){
        $this->registerRoute("GET",$uri,$controller,$middleware);
    }
    /**
     * 添加一个 Post 路由
     * @param string $url
     * @param string $controller
     * @return void
     */
    public function addPost($uri,$controller,$middleware=[]){
        $this->registerRoute("POST",$uri,$controller,$middleware);
    }
    /**
     * 添加一个 PUT 路由
     * @param string $url
     * @param string $controller
     * @return void
     */
    public function addPut($uri,$controller,$middleware=[]){
        $this->registerRoute("PUT",$uri,$controller,$middleware);
    }
    /**
     * 添加一个 Post 路由
     * @param string $url
     * @param string $controller
     * @return void
     */
    public function addDelete($uri,$controller,$middleware=[]){
        $this->registerRoute("DELETE",$uri,$controller,$middleware);
    }

    public function route($uri){
        $requestMethod = $_SERVER['REQUEST_METHOD'];

        if ($requestMethod === 'POST' && isset($_POST['_method'])) {

            $requestMethod = strtoupper($_POST['_method']);
        }

        $uriSegments = explode('/',trim($uri,'/'));
        
       
        foreach($this->routes as $route){

            $routeSegments = explode('/',trim($route['uri'],'/'));
            $match=false;
            if(count($uriSegments) === count($routeSegments) && strtoupper($route['method']===$requestMethod)){
                $params = [];
                $match = true;
                for( $i = 0; $i < count($uriSegments) ; $i++){
                    if($routeSegments[$i] !== $uriSegments[$i] && !preg_match('/\{(.+?)\}/',$routeSegments[$i])){
                        $match = false;
                        break;
                    }
                    if (preg_match('/\{(.+?)\}/',$routeSegments[$i],$matchs)) {
                        $params[$matchs[1]]=$uriSegments[$i];
                    }
                }
             }
            if ($match) {

                foreach ($route['middleware'] as $middleware){
                    (new Authorise()) -> handle($middleware);
                }

                $controller = 'App\\Controllers\\' . $route['controller'];
                $controllerMethod = $route['controllerMethod'];
                
                $controllerInstance = new $controller();
                $controllerInstance->$controllerMethod($params);               
                return;
            }
        }

      ErrorController::notFound();

    }


    public function error($httpCode = 404)
{
    http_response_code($httpCode);
    loadView("error/{$httpCode}");
    exit;
}
}


// $routes = require basePath('routes.php');
// if( array_key_exists($uri, $routes)){
//     require(basePath($routes[$uri]));
// }else{
//         http_response_code(404);
//     require(basePath($routes['404']));

// }